import json
import logging
import os
from datainit import *


# 当文件不存在时，输出文件


def init_file(filename):
    if filename == "data.json":
        res = {
            "background": "default.jpg",
            "size": [1980, 1080],
            "time": [[8, 40]],
            "dic": {
                "local": ["kbList"],
                "name": "kcmc",
                "teacher": "xm",
                "week": "zcd",
                "part": "jcor",
                "weekday": "xqjmc",
                "address": "cdmc"
            }
        }
        save_file(filename)
        return res
    if filename == "class.json":
        res = {
            "date_start": [
                2020,
                1,
                1
            ],
            "color": {
                "love and peace": "#9998888"
            },
            "subject": {
                "1010101010101010": {
                    "name": "love and peace",
                    "day": 1,
                    "week": [
                        1
                    ],
                    "part": [
                        1,
                        2
                    ],
                    "teacher": "sir",
                    "address": "address"
                }
            }
        }
        save_file(filename)
        return res


def save_file(filename, dt):
    try:
        with open(filename, "w") as f:
            json.dump(dt, f)
    except IOError:
        logging.error("unable to save file {}".format(filename))


def read_file(filename=""):
    try:
        if os.path.isfile(filename):
            with open(filename, "r") as f:
                return json.loads(f.read())
        else:
            return init_file(filename)
    except IOError:
        logging.error("unable to open file {}".format(filename))


def change_class():
    pass


def add_class(dic):
    pass


def import_class(cjs, dic, cls=Classes()):
    js = cjs
    for site in dic["dic"]["local"]:
        js = js[site]
    for classes in js:
        cl = AClass(classes["name"], day=classes["weekday"], week=classes["week"],
                    part=classes["part"], teacher=classes["teacher"], address=classes[classes])
        cls.append(cl)
